<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2020/8/2
 * Time: 16:27
 */
class serv_rapi_wishU extends L {

    public static $url = "https://www.wishpost.cn/api/";
    /**
     * 描述 : 用code获取token
     * 作者 : Zoro.Zhu
     */
    public static function codeToken($code,$clientId,$secret){
        $url = self::$url . "v2/oauth/access_token";
        $xml = "<?xml version=\"1.0\" ?>
        <root>
            <client_id>{$clientId}</client_id>
            <client_secret>{$secret}</client_secret>
            <redirect_uri>https://6beams.com/serv/accreditwishU.php</redirect_uri>
            <grant_type>authorization_code</grant_type>
            <code>{$code}</code>
        </root>";
        $res = of_base_com_net::request($url, ['post' => $xml]);
        p($res);
        if(!empty($res['state'])){
            libxml_disable_entity_loader(true);
            $xmlString = simplexml_load_string($res['response'], 'SimpleXMLElement', LIBXML_NOCDATA);
            return json_decode(json_encode($xmlString),true);
        }else{
            return [];
        }
    }

    /**
     * 描述 : 刷新token
     * 作者 : Zoro.Zhu
     **/
    public static function refreshToken($data) {
        $url = self::$url . "v2/oauth/refresh_token";
        $xml = "<?xml version=\"1.0\" ?>
        <root>
            <client_id>{$data['appKey']}</client_id>
            <client_secret>{$data['appSecret']}</client_secret>
            <refresh_token>{$data['refreshToken']}</refresh_token>
            <grant_type>refresh_token</grant_type>
        </root>";
        $res = of_base_com_net::request($url, ['post' => $xml]);
        if(!empty($res['state'])){
            libxml_disable_entity_loader(true);
            $xmlString = simplexml_load_string($res['response'], 'SimpleXMLElement', LIBXML_NOCDATA);
            return json_decode(json_encode($xmlString),true);
        }else if(empty($data['retry']) || $data['retry'] < 3){
            //重试3次
            $data['retry'] = !empty($data['retry']) ? $data['retry'] + 1 : 1;
            self::refreshToken($data);
        }else{
            return [];
        }
    }

    /**
     * 描述 : 获取订单的物流账单
     * 作者 : Zoro.Zhu
     */
    public static function getOrderPayment($token,$tracking = []){
        $url = self::$url . "v3/get_order_payment";
        $post = [
            'access_token' => $token,
            'tracking_ids' => $tracking,
        ];
        $res = of_base_com_net::request($url, [
            'post' => json_encode($post),
        ]);
        if($res['state']){
            $response = json_decode($res['response'], true);
            if(!empty($response['data'])){
                $logistics = [];
                foreach($response['data'] as $row){
                    $logistics[$row['tracking_id']] = $row;
                };
                return $logistics;
            }
        }
        return [];
    }

}
return true;